#include <Arduino.h>
#include <Ds1302.h>

//计时模块DS1302相关定义
#define RST 10    //ds1302的RST引脚定义
#define DATA 3    //ds1302的DATA引脚定义
#define CLK 2     //ds1302的CLK引脚定义

Ds1302 rtc(RST, CLK, DATA); //创建DS1302这个对象

void setup()
{
  //初始化串口
  Serial.begin(9600);

  //初始化DS1302
  rtc.init();

  //测试时钟是否停止并设置一个日期时间来启动它
  if (rtc.isHalted())
  {
      Serial.println("RTC is halted. Setting time...");

      //创建基于DS1302库下的时间参数
      Ds1302::DateTime dt = {
          .year = 24,
          .month = Ds1302::MONTH_JUL,
          .day = 27,
          .hour = 14,
          .minute = 13,
          .second = 0,
          .dow = Ds1302::DOW_SAT
      };

      //将设置的时间写入DS1302模块
      rtc.setDateTime(&dt);
  }
  else
  {
    Serial.println("RTC is busy.\r\n");
  }
    

  Serial.println("Time start.\r\n");
}


void loop()
{
    char outputString[100]={0};
    Ds1302::DateTime now;
    //获取当前时间并且存储在now中
    rtc.getDateTime(&now);

    static uint8_t last_second = 0;
    //如果秒数发生更新
    if (last_second != now.second)
    {
        //手动更新秒数，方便下次判断
        last_second = now.second;
        //格式化字符串
        sprintf(outputString, 
        "%d-%d-%d %d  %d:%d:%d\r\n",
        now.year+2000,
        now.month,
        now.day,
        now.dow,
        now.hour,
        now.minute,
        now.second );
        //输出字符串
        Serial.println(outputString);
    }
    delay(1000);
}